<template>
  <div class="result-layout">
    <div class="side-bar">
      <div class="result-return">
        <el-button type="text" @click="goBack">返回</el-button>
      </div>
      <SideTabs
        :tabs="sideTabs"
        :activeTab="activeSideTab"
        @jump="onSidebarJump"
      />
    </div>
    <div class="main-content scrollable-content" ref="mainContentRef">
      <div class="main-inner">
        <div class="main-inner-content">
          2025年7月 - 组织氛围测评问卷 - 分析报告

          <div>
            <el-button
              type="primary"
              @click="exportReport"
              :loading="buttonLoading"
              class="export-btn"
            >
              <img src="/export.svg" alt="导出报告" class="export-icon" />
              导出报告
            </el-button>
          </div>
        </div>
        <template v-if="!isLoading">
          <StatCard :cards="topStatCards" />
        </template>
        <template v-else>
          <el-skeleton :rows="1" animated style="margin-bottom: 24px" />
        </template>
        <div
          v-for="section in analysisSections"
          :key="section.key"
          :id="section.key"
          class="analysis-section"
        >
          <div class="table-section">
            <template v-if="!isLoading">
              <SimpleTable
                :detailColumns="section.detailColumns"
                :detailData="sectionDetailData[section.key]"
                :title="section.title"
                :totalColumns="section.totalColumns"
                :totalData="sectionTotalData[section.key]"
                :filters="filterOptions"
                :checked-filters="sectionFilters[section.key]"
                @filter-change="(val) => onFilterChange(section.key, val)"
              />
            </template>
            <template v-else>
              <el-skeleton :rows="8" animated />
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  onUnmounted,
  computed,
  watch,
  nextTick,
} from "vue";
import { ElSkeleton } from "element-plus";
import { throttle } from "@/utils/throttle";
import SideTabs from "./SideTabs.vue";
import SimpleTable from "./SimpleTable.vue";
import StatCard from "./StatCard.vue";
import {
  getSatisfactionAnalysis,
  getEngagementAnalysis,
  getSurveyStatistics,
} from "@/api/api";
import { useRouter } from "vue-router";
import { exportElementWithSections } from "@/utils/exportPdf";
const router = useRouter();
const buttonLoading = ref(false);
const isLoading = ref(true);
function goBack() {
  router.replace("/start/result");
}

const satisResData = ref({}); // 存所有类型原始数据，key为analysisType
const indicatorResData = ref({}); // 存项目汇总分析原始数据
const analysisSections = ref([]);
const topStatCards = ref([]);
const filterOptions = ref([
  { label: "1 强烈不同意", value: 1 },
  { label: "2 不同意", value: 2 },
  { label: "3 略有异议", value: 3 },
  { label: "4 基本同意", value: 4 },
  { label: "5 同意", value: 5 },
  { label: "6 强烈同意", value: 6 },
]);

onMounted(async () => {
  initData();
  attachScrollListener();
});

onUnmounted(() => {
  detachScrollListener();
});

let scrollHandler = null;
function attachScrollListener() {
  const content = mainContentRef.value;
  if (!content) return;
  scrollHandler = throttle(updateActiveTabOnScroll, 150);
  content.addEventListener("scroll", scrollHandler);
}

function detachScrollListener() {
  const content = mainContentRef.value;
  if (content && scrollHandler) {
    content.removeEventListener("scroll", scrollHandler);
  }
}

function updateActiveTabOnScroll() {
  const content = mainContentRef.value;
  if (!content) return;
  const sections = Array.from(content.querySelectorAll(".analysis-section"));
  const contentRect = content.getBoundingClientRect();
  const centerY = contentRect.top + contentRect.height / 2;

  // 在中心线经过的 section 即为当前 section
  const target = sections.find((sec) => {
    const rect = sec.getBoundingClientRect();
    return rect.top <= centerY && rect.bottom >= centerY;
  });

  const currentId =
    target?.getAttribute("id") || sections[0]?.getAttribute("id") || "";
  if (currentId && activeSideTab.value !== currentId) {
    activeSideTab.value = currentId;
  }
}

// 封装接口请求
const fetchAnalysisData = async (params) => {
  const res = await getSatisfactionAnalysis({ surveyId: 1, params }); // 满意度分析
  return res.data.data;
};
const fetchEngagementData = async (params) => {
  const res = await getEngagementAnalysis({ surveyId: 1, params }); // 敬业度分析
  return res.data.data;
};

const analysisTypeList = [
  { type: "PERSONNEL", label: "人员" },
  { type: "TENURE", label: "司龄" },
  { type: "PERFORMANCE", label: "绩效" },
  { type: "DEPARTMENT", label: "部门" },
];

const initData = async () => {
  analysisSections.value = [];
  satisResData.value = {};
  indicatorResData.value = {};
  getSurveyStatisticsData();
  await getData(fetchAnalysisData);
  await getData(fetchEngagementData);
  isLoading.value = false;
};

const getSurveyStatisticsData = async () => {
  const res = await getSurveyStatistics();
  topStatCards.value = res.data.data;
};

const getData = async (fetchFn) => {
  const analysisKind = fetchFn === fetchAnalysisData ? "SATIS" : "ENGAGE"; // 用于区分数据来源
  //
  for (const item of analysisTypeList) {
    const analysisKey = `${analysisKind}_${item.type}`;
    const paramsQuestion = {
      granularity: "QUESTION", //按题目分析
      analysisType: item.type,
    };
    const paramsIndicator = {
      granularity: "INDICATOR", //按指标分析
      analysisType: item.type,
      scoreRange: "5,6", // 默认统计 5、6 分档
    };
    try {
      const data = await fetchFn(paramsQuestion); // 具体指标分析
      const dataIndicator = await fetchFn(paramsIndicator); // 项目汇总分析
      indicatorResData.value[analysisKey] = dataIndicator;
      satisResData.value[analysisKey] = data;
      const groups = Object.keys(data);
      // 收集所有题目，按接口出现顺序依次去重，保证顺序 = 后端顺序
      const allQuestions = [];
      groups.forEach((g) => {
        Object.keys(data[g]).forEach((qKey) => {
          if (!allQuestions.includes(qKey)) allQuestions.push(qKey);
        });
      });
      // 处理项目汇总分析 → 生成 totalColumns 与 totalData
      const summaryGroups = Object.keys(dataIndicator || {});
      // 同理：遍历所有 summaryGroup 收集 indicator 顺序
      const indicators = [];
      summaryGroups.forEach((g) => {
        Object.keys(dataIndicator[g] || {}).forEach((ind) => {
          if (!indicators.includes(ind)) indicators.push(ind);
        });
      });
      const totalColumns = [
        { label: "序号", prop: "index", width: "60px" },
        { label: "指标", prop: "indicator", width: "160px" },
        ...summaryGroups.map((g) => ({ label: g, prop: g, width: "120px" })),
      ];
      const generateTotalData = (checkedFilters) => {
        return indicators.map((indName, idx) => {
          const row = {
            index: String(idx + 1).padStart(2, "0"),
            indicator: indName,
          };
          summaryGroups.forEach((g) => {
            const info = dataIndicator[g]?.[indName] ?? {};
            if (info.scorePercentages) {
              const sp = info.scorePercentages;
              const sum = (checkedFilters || [5, 6]).reduce(
                (acc, i) => acc + (sp[`score${i}`] ?? 0),
                0
              );
              row[g] = sum + "%";
            } else {
              const percent = info.percent ?? 0;
              row[g] = percent * 100 + "%";
            }
          });
          return row;
        });
      };

      const totalData = generateTotalData([5, 6]);
      //处理具体指标分析
      analysisSections.value.push({
        key: `${analysisKind.toLowerCase()}-indicator-detail-${item.type}`,
        title:
          fetchFn === fetchAnalysisData
            ? `满意度-${item.label}`
            : `敬业度-${item.label}`,
        detailColumns: [
          { label: "序号", prop: "index", width: "60px" },
          { label: "具体问题", prop: "question", width: "320px" },
          ...groups.map((g) => ({ label: g, prop: g, width: "120px" })),
        ],
        totalColumns,
        totalData,
        summaryGroups,
        indicators,
        generateTotalData,
        allQuestions,
        groups,
        analysisKey,
      });
    } catch (e) {
      console.error(`分析接口请求失败: ${item.type}`, e);
    }
  }
};

const sideTabs = computed(() =>
  analysisSections.value.map((s) => ({
    label: s.title,
    anchor: s.key,
  }))
);
const activeSideTab = ref("person");
const sectionFilters = reactive({});
watch(
  analysisSections,
  (sections) => {
    sections.forEach((section) => {
      if (
        !sectionFilters[section.key] ||
        !Array.isArray(sectionFilters[section.key])
      ) {
        sectionFilters[section.key] = [5, 6];
      }
    });
    Object.keys(sectionFilters).forEach((key) => {
      if (!sections.find((s) => s.key === key)) {
        delete sectionFilters[key];
      }
    });
  },
  { immediate: true, deep: true }
);
// 将选中评分数组转换为后端需要的 scoreRange 字符串，统一使用逗号分隔，例如 [1,2,3] -> "1,2,3"
function buildScoreRangeString(arr) {
  if (!arr || arr.length === 0) return "";
  return [...arr].sort((a, b) => a - b).join(",");
}

const onFilterChange = async (sectionKey, val) => {
  const arr = sectionFilters[sectionKey];
  if (arr.includes(val)) {
    sectionFilters[sectionKey] = arr.filter((v) => v !== val);
  } else {
    sectionFilters[sectionKey] = [...arr, val];
  }

  // 重新调取项目汇总分析接口
  const section = analysisSections.value.find((s) => s.key === sectionKey);
  if (!section) return;

  const analysisKey = section.analysisKey; // 如 SATIS_PERSONNEL
  const [analysisKind, analysisType] = analysisKey.split("_");
  const scoreRange = buildScoreRangeString(sectionFilters[sectionKey]);

  const paramsIndicator = {
    granularity: "INDICATOR",
    analysisType,
    scoreRange,
  };

  try {
    let dataIndicator;
    if (analysisKind === "SATIS") {
      dataIndicator = await fetchAnalysisData(paramsIndicator);
    } else {
      dataIndicator = await fetchEngagementData(paramsIndicator);
    }
    indicatorResData.value[analysisKey] = dataIndicator;
  } catch (e) {
    console.error("更新项目汇总分析失败", e);
  }
};

//筛选
// 多 section 动态 detailData (具体指标分析)
const sectionDetailData = computed(() => {
  const result = {};
  analysisSections.value.forEach((section) => {
    const { allQuestions, groups, key, analysisKey } = section;
    const raw = satisResData.value[analysisKey];
    if (!raw) {
      result[key] = [];
      return;
    }
    result[key] = allQuestions.map((qKey, idx) => {
      const row = {
        index: String(idx + 1).padStart(2, "0"),
        question: raw[groups[0]][qKey].questionText,
      };
      groups.forEach((g) => {
        const sp = raw[g][qKey]?.scorePercentages || {};
        const checked = sectionFilters[key] || [5, 6];
        const sum = checked.reduce((acc, i) => acc + (sp[`score${i}`] ?? 0), 0);
        row[g] = sum + "%";
      });
      return row;
    });
  });
  return result;
});

// 多 section 动态 totalData (项目汇总分析)
const sectionTotalData = computed(() => {
  const result = {};
  analysisSections.value.forEach((section) => {
    const { key, analysisKey } = section;
    const raw = indicatorResData.value[analysisKey];
    if (!raw) {
      result[key] = [];
      return;
    }
    const summaryGroups = Object.keys(raw);
    const indicators =
      summaryGroups.length > 0 ? Object.keys(raw[summaryGroups[0]] || {}) : [];

    result[key] = indicators.map((indName, idx) => {
      const row = {
        index: String(idx + 1).padStart(2, "0"),
        indicator: indName,
      };
      summaryGroups.forEach((g) => {
        const info = raw[g]?.[indName] ?? {};
        const percent = info.percent ?? 0;
        row[g] = percent * 100 + "%";
      });
      return row;
    });
  });
  return result;
});

const mainContentRef = ref(null);
function onSidebarJump(anchor) {
  activeSideTab.value = anchor;
  const mainContent = mainContentRef.value;
  const target = document.getElementById(anchor);
  if (mainContent && target) {
    const mainRect = mainContent.getBoundingClientRect();
    const targetRect = target.getBoundingClientRect();
    // 将目标 section 顶部对齐到内容区顶部
    const scrollTop = mainContent.scrollTop + (targetRect.top - mainRect.top);
    mainContent.scrollTo({ top: scrollTop, behavior: "smooth" });
  }
}

//导出pdf
const exportReport = async () => {
  buttonLoading.value = true;
  await exportElementWithSections(
    mainContentRef.value,
    ".analysis-section",
    "分析报告.pdf",
    { scale: 1, quality: 0.6 }
  );
  buttonLoading.value = false;
};
</script>

<style scoped>
.result-layout {
  display: flex;
  height: 100vh; /* 固定高度，避免外层出现滚动条 */
  width: 100%;
  background: #f8f9fb;
  align-items: stretch;
  overflow: hidden; /* 只允许内部容器滚动 */
}
.side-bar {
  width: 200px;
  min-width: 160px;
  flex: 0 0 200px;
  background: #f8f9fb;
  border-radius: 0 24px 24px 0;
  height: 100vh;
  box-shadow: none;
  z-index: 2;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-left: 0;
  padding-top: 32px;
}
.result-return {
  width: 168px;
  margin: 0 auto 24px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
  padding: 0 0 0 0;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}
.result-return .el-button {
  width: 100%;
  height: 48px;
  border-radius: 16px;
  font-size: 16px;
  font-weight: 500;
  color: #222;
  text-align: left;
  justify-content: flex-start;
  padding-left: 18px;
  background: transparent;
  border: none;
  display: flex;
  align-items: center;
  gap: 6px;
}
.result-return .el-button:before {
  content: "";
  display: inline-block;
  width: 18px;
  height: 18px;
  margin-right: 4px;
  background: url('data:image/svg+xml;utf8,<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M11.25 14.25L6.75 9.75L11.25 5.25" stroke="%23226CF2" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>')
    no-repeat center center;
  background-size: 18px 18px;
}
.main-content {
  flex: 1;
  padding: 32px 0;
  min-width: 0;
  height: 100%; /* 充满父容器，高度由父容器控制 */
  overflow-y: auto;
  background: #f6f9fb;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
}
.main-inner {
  width: 100%;
  margin: 0 auto; /* 居中 */
  padding: 0 16px; /* 保持少量内边距 */
  box-sizing: border-box;
}
.main-inner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  font-size: 18px;
  font-weight: 700;
  color: #333333;
}
.export-icon {
  width: 18px;
  height: 20px;
  margin-right: 8px;
}
.export-btn {
  margin-left: 16px;
  display: flex;
  background-color: #1f69ff;
  border-radius: 10px;
  padding: 10px 20px;
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  height: 40px;
}
.main-content::-webkit-scrollbar {
  width: 0 !important;
  background: transparent;
}

.table-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.03);
  padding: 24px 24px 12px 24px; /* 与 main-inner padding 协调 */
  margin-top: 32px;
  width: 100%;
  box-sizing: border-box;
}
</style>
